<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="form" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="角色名称">
              <el-input
                v-model="listQuery.role"
                placeholder="角色名称"
                style="width: 200px;"
                class="filter-item"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="角色描述">
              <el-input
                v-model="listQuery.description"
                placeholder="角色描述"
                style="width: 200px;"
                class="filter-item"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList">查询</el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          class="filter-item"
          @click="addDept"
          v-if="hasPermission('clinic:role:add')"
        >
          <span>新增角色</span>
        </el-button>
      </el-form>
    </div>
    <div>
      <h3>角色管理#</h3>
    </div>

    <!--功能点授权-->
    <el-dialog :title="title" class="dialogAdd" :visible.sync="dialogAddgsVisible" :width="width" top="30px">
      <template>
        <el-input
          v-model="permListQuery.title"
          placeholder="菜单名称"
          style="width: 200px;"
          class="filter-item"
        />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getPermList">查询</el-button>
      </template>

      <template>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="setPerm">授权</el-button>
      </template>

      <tree-table
        :height="tableHeight"
        :data="permList"
        :columns="columns"
        :root_value="'0'"
        :primary_fld="'id'"
        :expand-all="expandAll"
        :parent_fld="'parentId'"
        :select_fld="'false'"
        ref="treeTable"
      >
        <el-table-column label="类别" min-width="75" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.icon? "菜单权限":"功能权限"}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="75" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.available? "已授权":"未授权"}}</span>
          </template>
        </el-table-column>
      </tree-table>
    </el-dialog>

    <!--角色列表-->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <!--{"id":1,"available":true,"description":"超级管理员","role":"admin","showOrder":""}-->

      <!--<el-table-column label="全选" prop="id" align="center" width="100" >
        <label style="padding-right: 10px;font-size: 15px;font-weight: 500;"><input name="Fruit" type="checkbox"
                                                                                    value=""/> </label>
      </el-table-column>-->
      <el-table-column label="角色名称" prop="id" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{row.role}}</span>
        </template>
      </el-table-column>

      <el-table-column label="角色描述" prop="id" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{row.description}}</span>
        </template>
      </el-table-column>

      <el-table-column label="启用" prop="id" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{row.available? "启用":"未启用"}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" prop="id" align="center" width="180">
        <template slot-scope="{row}">
          <!--          <el-button type="primary" size="mini" @click="DeptDelete">删除</el-button>-->
          <el-button
            type="primary"
            size="mini"
            v-if="hasPermission('clinic:role:perm:edit')"
            @click="menuPermissions(row.id,row.role,row.description)"
          >菜单授权</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--<pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />-->

    <el-dialog :title="roleTitle" class="dialogAdd" :visible.sync="dialogRoleVisible" @close="onClose">
      <el-form ref="addForm" :model="addData" :rules="addRules" size="medium" label-width="100px">
        <el-form-item label="角色名称" prop="role">
          <el-input v-model="addData.role" placeholder="请输入单行文本角色名称" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="addData.description" placeholder="请输入角色描述" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="启用" prop="available" required>
          <el-switch v-model="addData.available"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { getRoles, getRolePerms, getRoleInfo, editRolePerms,addRole } from "@/api/role";
  import { getPermList } from "@/api/perm";
  import Pagination from "@/components/Pagination";
  import treeTable from "@/components/treeTable/permTree.vue";

  export default {
    name: "rolePerm",
    components: { Pagination, treeTable },
    data() {
      return {
        dialogRoleVisible:false,
        roleTitle:"",
        addData: {
          role: null,
          description: null,
          available: true,
        },
        addRules: {
          role: [{
            required: true,
            message: '请输入单行文本角色名称',
            trigger: 'blur'
          }],
          description: [{
            required: false,
            message: '请输入角色描述',
            trigger: 'blur'
          }],
        },
        width: "800px",
        tableKey: 0,
        listLoading: true,
        list: null,
        driver: null,
        listData: null,
        total: 0,
        listQuery: {
          page: 1,
          pageSize: 10
        },

        RoleInfo: {},

        permList: [],
        permListQuery: {},

        addForm: {
          name: "",
          creditCode: "",
          address: "",
          tel: "",
          id: ""
        },
        dialogAddgsVisible: false,
        title: "",

        tableHeight: 500,
        expandAll: true,
        columns: [{ value: "description", text: "菜单", minWidth: "300" }]
      };
    },
    filters: {
      checkStatus: function(s) {
        return s === 1 ? "授权" : "未授权";
      }
    },
    created() {
      this.getList();
    },
    mounted: function() {
      let self = this;
      self.width = window.innerWidth * 0.8 + "px"
      // 监听窗口大小变化
      /* let self = this;
      window.onresize = function() {
        self.tableHeight =
          window.innerHeight -
          self.$refs.treeTable.$el.offsetTop -
          document.getElementsByClassName("navbar")[0].parentNode.clientHeight;
      }; */
    },
    methods: {
      onClose() {
        this.$refs['addForm'].resetFields()
      },
      close() {
        this.$emit('update:visible', false)
      },
      handelConfirm() {
        this.$refs['addForm'].validate(valid => {
          if (!valid) return
          addRole(this.addData).then(data => {
            console.log(data);
            if (data.code === 200) {
              this.$message({
                showClose: true,
                message: data.msg,
                type: "success",
              });
              this.getList();
              this.dialogAddgsVisible = false;
            }
          });
          this.close()
        })
      },
      setPerm() {
        let dataSet = {
          id: this.permListQuery.roleId,
          idx: []
        };
        this.permList.map(item => {
          if (item["false"]) {
            dataSet.idx.push(item.id);
          }
        });
        console.log(dataSet);

        editRolePerms(dataSet).then(data => {
          console.log(data);
          if (data.code === 200) {
            //授权成功
            this.$message("授权成功");
            this.dialogAddgsVisible = false;
            if (this.permListQuery.description === this.$store.getters.roleName) {
              this.open();
            }
          }
        });
      },

      open() {
        this.$confirm("修改了当前用户角色权限, 是否刷新页面?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            window.location.reload();
          })
          .catch(() => {
          });
      },

      addDept() {
        {
          this.dialogRoleVisible = true;
          this.roleTitle = "新增角色";
        }
      },
      getList() {
        console.log(this);
        this.listLoading = true;

        getRoles(this.listQuery).then(response => {
          this.list = response.data;
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false;
          }, 0.5 * 1000);
        });
      },
      menuPermissions(id, role, description) {
        this.dialogAddgsVisible = true;
        this.title = "菜单授权";
        this.permListQuery.roleId = id;
        this.permListQuery.description = description;
        this.getPermList();
      },
      getPermList() {
        console.log(this);
        getRolePerms(this.permListQuery).then(response => {
          this.permList = response.page;

          console.log(this.permList);

          this.permList.map(row => {
            row.id = row.id + ""
            row.parentId = row.parentId + ""
            if (row.available) {
              this.$refs.treeTable.chooseNode(row);
            }
          });

          setTimeout(() => {
            this.listLoading = false;
          }, 0.5 * 1000);
        });
      }
    }
  };
</script>

<style scoped>
  .edit-input {
    padding-right: 100px;
  }

  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
